<template>
  <div class="profile-page">
    <div class="profile-container">
      <!-- 页面标题 -->
      <div class="page-header">
        <h2>个人资料</h2>
        <p>管理您的个人信息和学习设置</p>
      </div>

      <div class="profile-content">
        <!-- 基本信息 -->
        <div class="profile-section">
          <div class="section-header">
            <h3>基本信息</h3>
            <el-button type="primary" @click="saveBasicInfo" :loading="saving">
              保存更改
            </el-button>
          </div>
          
          <el-form
            :model="basicInfo"
            :rules="basicInfoRules"
            ref="basicInfoFormRef"
            label-width="100px"
            class="profile-form"
          >
            <div class="form-row">
              <el-form-item label="头像" prop="avatar">
                <div class="avatar-upload">
                  <el-avatar 
                    :size="100" 
                    :src="basicInfo.avatar || 'https://via.placeholder.com/100x100/409EFF/ffffff?text=用户'" 
                  />
                  <el-button type="primary" size="small" @click="uploadAvatar">
                    更换头像
                  </el-button>
                </div>
              </el-form-item>
            </div>
            
            <div class="form-row">
              <el-form-item label="用户名" prop="userName">
                <el-input v-model="basicInfo.userName" disabled />
              </el-form-item>
              <el-form-item label="昵称" prop="nickName">
                <el-input v-model="basicInfo.nickName" placeholder="请输入昵称" />
              </el-form-item>
            </div>
            
            <div class="form-row">
              <el-form-item label="真实姓名" prop="realName">
                <el-input v-model="basicInfo.realName" placeholder="请输入真实姓名" />
              </el-form-item>
              <el-form-item label="性别" prop="gender">
                <el-select v-model="basicInfo.gender" placeholder="请选择性别">
                  <el-option label="男" value="male" />
                  <el-option label="女" value="female" />
                  <el-option label="保密" value="secret" />
                </el-select>
              </el-form-item>
            </div>
            
            <div class="form-row">
              <el-form-item label="手机号码" prop="phone">
                <el-input v-model="basicInfo.phone" placeholder="请输入手机号码" />
              </el-form-item>
              <el-form-item label="邮箱地址" prop="email">
                <el-input v-model="basicInfo.email" placeholder="请输入邮箱地址" />
              </el-form-item>
            </div>
            
            <div class="form-row">
              <el-form-item label="出生日期" prop="birthday">
                <el-date-picker
                  v-model="basicInfo.birthday"
                  type="date"
                  placeholder="选择出生日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
              <el-form-item label="所在地区" prop="location">
                <el-cascader
                  v-model="basicInfo.location"
                  :options="locationOptions"
                  placeholder="请选择所在地区"
                />
              </el-form-item>
            </div>
            
            <div class="form-row">
              <el-form-item label="个人简介" prop="bio">
                <el-input
                  v-model="basicInfo.bio"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入个人简介"
                />
              </el-form-item>
            </div>
          </el-form>
        </div>

        <!-- 学习信息 -->
        <div class="profile-section">
          <div class="section-header">
            <h3>学习信息</h3>
          </div>
          
          <div class="learning-info">
            <div class="info-grid">
              <div class="info-item">
                <div class="info-label">学习等级</div>
                <div class="info-value">
                  <el-tag type="success">{{ learningInfo.level }}</el-tag>
                </div>
              </div>
              <div class="info-item">
                <div class="info-label">学习天数</div>
                <div class="info-value">{{ learningInfo.totalDays }} 天</div>
              </div>
              <div class="info-item">
                <div class="info-label">完成课程</div>
                <div class="info-value">{{ learningInfo.completedCourses }} 门</div>
              </div>
              <div class="info-item">
                <div class="info-label">通过考试</div>
                <div class="info-value">{{ learningInfo.passedExams }} 次</div>
              </div>
              <div class="info-item">
                <div class="info-label">成就点数</div>
                <div class="info-value">{{ learningInfo.achievementPoints }} 点</div>
              </div>
              <div class="info-item">
                <div class="info-label">注册时间</div>
                <div class="info-value">{{ learningInfo.registerDate }}</div>
              </div>
            </div>
          </div>
        </div>

        <!-- 密码修改 -->
        <div class="profile-section">
          <div class="section-header">
            <h3>密码修改</h3>
            <el-button type="primary" @click="changePassword" :loading="changingPassword">
              修改密码
            </el-button>
          </div>
          
          <el-form
            :model="passwordForm"
            :rules="passwordRules"
            ref="passwordFormRef"
            label-width="100px"
            class="profile-form"
          >
            <div class="form-row">
              <el-form-item label="当前密码" prop="currentPassword">
                <el-input
                  v-model="passwordForm.currentPassword"
                  type="password"
                  placeholder="请输入当前密码"
                  show-password
                />
              </el-form-item>
            </div>
            
            <div class="form-row">
              <el-form-item label="新密码" prop="newPassword">
                <el-input
                  v-model="passwordForm.newPassword"
                  type="password"
                  placeholder="请输入新密码"
                  show-password
                />
              </el-form-item>
              <el-form-item label="确认密码" prop="confirmPassword">
                <el-input
                  v-model="passwordForm.confirmPassword"
                  type="password"
                  placeholder="请再次输入新密码"
                  show-password
                />
              </el-form-item>
            </div>
          </el-form>
        </div>

        <!-- 学习偏好设置 -->
        <!--<div class="profile-section">-->
          <!--<div class="section-header">-->
            <!--<h3>学习偏好</h3>-->
            <!--<el-button type="primary" @click="savePreferences" :loading="savingPreferences">-->
              <!--保存设置-->
            <!--</el-button>-->
          <!--</div>-->
          <!---->
          <!--<div class="preferences-form">-->
            <!--<div class="preference-item">-->
              <!--<div class="preference-label">学习提醒</div>-->
              <!--<div class="preference-control">-->
                <!--<el-switch v-model="preferences.studyReminder" />-->
                <!--<span class="preference-desc">每日学习提醒</span>-->
              <!--</div>-->
            <!--</div>-->
            <!---->
            <!--<div class="preference-item">-->
              <!--<div class="preference-label">邮件通知</div>-->
              <!--<div class="preference-control">-->
                <!--<el-switch v-model="preferences.emailNotification" />-->
                <!--<span class="preference-desc">接收邮件通知</span>-->
              <!--</div>-->
            <!--</div>-->
            <!---->
            <!--<div class="preference-item">-->
              <!--<div class="preference-label">学习目标</div>-->
              <!--<div class="preference-control">-->
                <!--<el-select v-model="preferences.studyGoal" placeholder="选择学习目标">-->
                  <!--<el-option label="JFT BASIC" value="jft" />-->
                  <!--<el-option label="特定技能" value="tokutei" />-->
                  <!--<el-option label="JLPT N3" value="jlpt_n3" />-->
                  <!--<el-option label="JLPT N2" value="jlpt_n2" />-->
                <!--</el-select>-->
              <!--</div>-->
            <!--</div>-->
            <!---->
            <!--<div class="preference-item">-->
              <!--<div class="preference-label">每日学习时长</div>-->
              <!--<div class="preference-control">-->
                <!--<el-select v-model="preferences.dailyStudyTime" placeholder="选择学习时长">-->
                  <!--<el-option label="30分钟" value="30" />-->
                  <!--<el-option label="1小时" value="60" />-->
                  <!--<el-option label="2小时" value="120" />-->
                  <!--<el-option label="3小时以上" value="180" />-->
                <!--</el-select>-->
              <!--</div>-->
            <!--</div>-->
          <!--</div>-->
        <!--</div>-->
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'

const userStore = useUserStore()

// 表单引用
const basicInfoFormRef = ref()
const passwordFormRef = ref()

// 加载状态
const saving = ref(false)
const changingPassword = ref(false)
const savingPreferences = ref(false)

// 基本信息
const basicInfo = reactive({
  userName: '',
  nickName: '',
  realName: '',
  gender: '',
  phone: '',
  email: '',
  birthday: '',
  location: [],
  bio: '',
  avatar: ''
})

// 基本信息验证规则
const basicInfoRules = {
  nickName: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '昵称长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

// 学习信息
const learningInfo = reactive({
  level: '',
  totalDays: 0,
  completedCourses: 0,
  passedExams: 0,
  achievementPoints: 0,
  registerDate: ''
})

// 密码表单
const passwordForm = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 密码验证规则
const passwordRules = {
  currentPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 学习偏好
const preferences = reactive({
  studyReminder: true,
  emailNotification: true,
  studyGoal: 'jft',
  dailyStudyTime: '60'
})

// 地区选项
const locationOptions = [
  {
    value: 'beijing',
    label: '北京市',
    children: [
      { value: 'haidian', label: '海淀区' },
      { value: 'chaoyang', label: '朝阳区' }
    ]
  },
  {
    value: 'shanghai',
    label: '上海市',
    children: [
      { value: 'huangpu', label: '黄浦区' },
      { value: 'xuhui', label: '徐汇区' }
    ]
  }
]

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const response = await getUserInfo()
    if (response.code === 200) {
      const userData = response.data
      Object.assign(basicInfo, {
        userName: userData.userName || '',
        nickName: userData.nickName || '',
        realName: userData.realName || '',
        gender: userData.gender || '',
        phone: userData.phone || '',
        email: userData.email || '',
        birthday: userData.birthday || '',
        location: userData.location || [],
        bio: userData.bio || '',
        avatar: userData.avatar || ''
      })
    } else {
      console.error('获取用户信息失败:', response.msg)
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
  }
}

// 获取用户学习统计
const fetchUserStats = async () => {
  try {
    const response = await getUserStats()
    if (response.code === 200) {
      const statsData = response.data
      Object.assign(learningInfo, {
        level: statsData.level || '初级',
        totalDays: statsData.totalDays || 0,
        completedCourses: statsData.completedCourses || 0,
        passedExams: statsData.passedExams || 0,
        achievementPoints: statsData.achievementPoints || 0,
        registerDate: statsData.registerDate || ''
      })
    } else {
      console.error('获取用户学习统计失败:', response.msg)
    }
  } catch (error) {
    console.error('获取用户学习统计失败:', error)
  }
}

// 获取用户偏好设置
const fetchUserPreferences = async () => {
  try {
    const response = await getUserPreferences()
    if (response.code === 200) {
      const prefsData = response.data
      Object.assign(preferences, {
        studyReminder: prefsData.studyReminder || true,
        emailNotification: prefsData.emailNotification || true,
        studyGoal: prefsData.studyGoal || 'jft',
        dailyStudyTime: prefsData.dailyStudyTime || '60'
      })
    } else {
      console.error('获取用户偏好设置失败:', response.msg)
    }
  } catch (error) {
    console.error('获取用户偏好设置失败:', error)
  }
}

// 保存基本信息
const saveBasicInfo = async () => {
  try {
    await basicInfoFormRef.value.validate()
    saving.value = true
    
    const response = await updateUserInfo(basicInfo)
    if (response.code === 200) {
      ElMessage.success('基本信息保存成功')
      // 更新store中的用户信息
      userStore.updateUser(basicInfo)
    } else {
      ElMessage.error(response.msg || '保存失败')
    }
  } catch (error) {
    if (error.message) {
      ElMessage.error(error.message)
    } else {
      ElMessage.error('请检查输入信息')
    }
  } finally {
    saving.value = false
  }
}

// 修改密码
const changePassword = async () => {
  try {
    await passwordFormRef.value.validate()
    changingPassword.value = true
    
    const response = await changeUserPassword(passwordForm)
    if (response.code === 200) {
      ElMessage.success('密码修改成功')
      
      // 清空表单
      passwordForm.currentPassword = ''
      passwordForm.newPassword = ''
      passwordForm.confirmPassword = ''
    } else {
      ElMessage.error(response.msg || '密码修改失败')
    }
  } catch (error) {
    if (error.message) {
      ElMessage.error(error.message)
    } else {
      ElMessage.error('密码修改失败，请检查输入信息')
    }
  } finally {
    changingPassword.value = false
  }
}

// 保存学习偏好
const savePreferences = async () => {
  try {
    savingPreferences.value = true
    
    const response = await updateUserPreferences(preferences)
    if (response.code === 200) {
      ElMessage.success('学习偏好保存成功')
    } else {
      ElMessage.error(response.msg || '保存失败')
    }
  } catch (error) {
    console.error('保存学习偏好失败:', error)
    ElMessage.error('保存失败')
  } finally {
    savingPreferences.value = false
  }
}

// 上传头像
const uploadAvatar = async () => {
  try {
    // 这里应该实现文件上传功能
    // const fileInput = document.createElement('input')
    // fileInput.type = 'file'
    // fileInput.accept = 'image/*'
    // fileInput.onchange = async (e) => {
    //   const file = e.target.files[0]
    //   if (file) {
    //     const formData = new FormData()
    //     formData.append('file', file)
    //     const response = await uploadFile(formData)
    //     if (response.code === 200) {
    //       basicInfo.avatar = response.data.url
    //       ElMessage.success('头像上传成功')
    //     }
    //   }
    // }
    // fileInput.click()
    
    ElMessage.info('头像上传功能开发中')
  } catch (error) {
    console.error('头像上传失败:', error)
    ElMessage.error('头像上传失败')
  }
}

// 初始化数据
const initData = async () => {
  try {
    // 并行加载所有数据
    await Promise.all([
      fetchUserInfo(),
      fetchUserStats(),
      fetchUserPreferences()
    ])
  } catch (error) {
    console.error('初始化数据失败:', error)
  }
}

onMounted(() => {
  initData()
})
</script>

<style scoped>
.profile-page {
  min-height: 100vh;
  background: #f5f7fa;
  padding: 20px 0;
}

.profile-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 0 20px;
}

.page-header {
  text-align: center;
  margin-bottom: 40px;
}

.page-header h2 {
  color: #2c3e50;
  margin: 0 0 10px 0;
  font-size: 2rem;
}

.page-header p {
  color: #666;
  margin: 0;
  font-size: 1.1rem;
}

.profile-content {
  display: flex;
  flex-direction: column;
  gap: 30px;
}

.profile-section {
  background: white;
  border-radius: 12px;
  padding: 30px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 25px;
  padding-bottom: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.section-header h3 {
  margin: 0;
  color: #2c3e50;
  font-size: 1.3rem;
}

.profile-form {
  max-width: 100%;
}

.form-row {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
}

.avatar-upload {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
}

.learning-info {
  margin-top: 20px;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
}

.info-item {
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  text-align: center;
}

.info-label {
  color: #666;
  font-size: 0.9rem;
  margin-bottom: 10px;
}

.info-value {
  color: #2c3e50;
  font-size: 1.1rem;
  font-weight: bold;
}

.preferences-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.preference-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px solid #f0f0f0;
}

.preference-item:last-child {
  border-bottom: none;
}

.preference-label {
  font-weight: bold;
  color: #2c3e50;
}

.preference-control {
  display: flex;
  align-items: center;
  gap: 15px;
}

.preference-desc {
  color: #666;
  font-size: 0.9rem;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .profile-container {
    padding: 0 15px;
  }
  
  .profile-section {
    padding: 20px;
  }
  
  .form-row {
    grid-template-columns: 1fr;
  }
  
  .info-grid {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .preference-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .section-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
}
</style> 